package site.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.List;

import site.template.ShopSimpleSiteTemplate;

import commerce.business.CommerceBusiness;
import commerce.hibernate.po.Shop;

public class ShopSiteCreateService {
	private CommerceBusiness bus = new CommerceBusiness();
	
//	// 生成静态网页的路径
//	private String filePath;
//	// 是否覆盖文件
//	private boolean flag;	
	
	// 店铺模板
	ShopSimpleSiteTemplate shopSite = null;
	
	public ShopSiteCreateService() {
		
	}
	
	// 生成或刷新店铺网页
	public void makeShopSite(String filePath, boolean flag) {
		List<Shop> sList = bus.getAllShop();
		shopSite = new ShopSimpleSiteTemplate(sList);
		// System.out.println(shopSite.getHtml());
		// System.out.println(filePath);
		writeHtml(filePath, shopSite.getHtml(), flag);
		// return null;
	}
	
	
	
	
	
	
	
	/*--------------------------------------------------------------------------------*/
	/**
	 * 
	 * @param filePath
	 *            文件的路径名 +文件名+格式
	 * @param info
	 *            html code
	 * @param flag
	 *            若文件已经存在，是否覆盖
	 */
	private synchronized void writeHtml(String filePath, String info,
			boolean flag) {
		System.out.println("----------------------------------------------------------------------" + filePath);
		PrintWriter pw = null;
		try {
			File writeFile = new File(filePath);
			boolean isExit = writeFile.exists();
			if (isExit != true) {
				writeFile.createNewFile();
			} else {
				if (flag) {
					writeFile.delete();
					writeFile.createNewFile();
				}
			}
			pw = new PrintWriter(new FileOutputStream(filePath, true));
			pw.println(info);
			pw.close();
		} catch (Exception e) {
			System.err.println( this.getClass() + "-------------------------------------" + e.getMessage());
			System.out.println(filePath);
		} finally {
			pw.close();
		}
	}
	
	public static void main(String[] args) {
		new ShopSiteCreateService().makeShopSite("f:/home/shop.html", true);
	}

}
